package com.customization.unionpay.market.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.io.IOException;
import java.util.Map;

public class HttpUtils {

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * get请求
     *
     * @param url     请求地址
     * @param headers 请求头参数
     * @return
     */
    public static String doGet(String url, Map<String, Object> headers, String encode, String decode) throws Exception {
        if (encode == null) {
            encode = "utf-8";
        }
        if (decode == null) {
            decode = "utf-8";
        }
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
            if (headers != null && !headers.isEmpty()) {
                for (String s : headers.keySet()) {
                    httpGet.setHeader(s, headers.get(s).toString());
                }
            }
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String jsons = EntityUtils.toString(entity);
            return new String(jsons.getBytes(decode), encode);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("关闭get-response请求出错：" + e.toString());
            }
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                log.error("关闭get-client请求出错：" + e.toString());
            }
        }
    }

    /**
     * get请求
     *
     * @param url     请求地址
     * @param headers 请求头参数
     * @return
     */
    public static JSONObject doGet(RequestConfig requestConfig, String url, Map<String, Object> headers, String encode, String decode) throws Exception {
        if (encode == null) {
            encode = "utf-8";
        }
        if (decode == null) {
            decode = "utf-8";
        }

        JSONObject res = new JSONObject();

        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(url);
            if(requestConfig != null){
                httpGet.setConfig(requestConfig);
            }
            httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
            if (headers != null && !headers.isEmpty()) {
                for (String s : headers.keySet()) {
                    httpGet.setHeader(s, headers.get(s).toString());
                }
            }
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            int statusCode = response.getStatusLine().getStatusCode();
            String jsons = EntityUtils.toString(entity);
            res.put("statusCode", statusCode);
            res.put("responseBosy", new String(jsons.getBytes(decode), encode));
            return res;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("关闭get-response请求出错：" + e.toString());
            }
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                log.error("关闭get-client请求出错：" + e.toString());
            }
        }
    }

    /**
     * post请求
     *
     * @param url
     * @param headers 请求头
     * @param params  请求数据
     * @return 响应数据
     */
    public static String doPost(String url, Map<String, Object> headers, JSONObject params, String encode, String decode) throws Exception {
        if (encode == null) {
            encode = "utf-8";
        }
        if (decode == null) {
            decode = "utf-8";
        }
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);

            if (headers != null) {
                for (String s : headers.keySet()) {
                    httpPost.setHeader(s, headers.get(s).toString());
                }
            }

            if (params != null) {
                String jsonStr = JSONObject.toJSONString(params);
                StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8");
                httpPost.setEntity(stringEntity);
            }

            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String jsons = EntityUtils.toString(entity);
            return new String(jsons.getBytes(decode), encode);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("关闭post-response请求出错：" + e.toString());
            }
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                log.error("关闭post-client请求出错：" + e.toString());
            }
        }
    }

    /**
     * post请求
     *
     * @param url
     * @param headers 请求头
     * @param params  请求数据
     * @return 响应数据
     */
    public static JSONObject doPost(RequestConfig requestConfig,String url, Map<String, Object> headers, String params, String encode, String decode) throws Exception {
        if (encode == null) {
            encode = "utf-8";
        }
        if (decode == null) {
            decode = "utf-8";
        }
        JSONObject res = new JSONObject();
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            if(requestConfig != null){
                httpPost.setConfig(requestConfig);
            }
            if (headers != null) {
                for (String s : headers.keySet()) {
                    httpPost.setHeader(s, headers.get(s).toString());
                }
            }

            if (params != null) {
                StringEntity stringEntity = new StringEntity(params, "UTF-8");
                httpPost.setEntity(stringEntity);
            }

            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String jsons = EntityUtils.toString(entity);

            int statusCode = response.getStatusLine().getStatusCode();
            res.put("statusCode", statusCode);
            res.put("responseBody",  new String(jsons.getBytes(decode), encode));
            return res;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("关闭post-response请求出错：" + e.toString());
            }
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                log.error("关闭post-client请求出错：" + e.toString());
            }
        }
    }

    /**
     * 发起PUT同步请求
     *
     * @param url
     * @param headers 请求头
     * @param params  请求数据
     * @return 响应数据
     */
    public static String doPut(String url, Map<String, Object> headers, Map<String, Object> params, String encode, String decode) throws Exception {
        if (encode == null) {
            encode = "utf-8";
        }
        if (decode == null) {
            decode = "utf-8";
        }
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClientBuilder.create().build();
            HttpPut httpPut = new HttpPut(url);
            httpPut.setHeader("Content-Type", "application/json;charset=UTF-8");
            if (headers != null) {
                for (String s : headers.keySet()) {
                    httpPut.setHeader(s, headers.get(s).toString());
                }
            }
            if (params != null) {
                String jsonStr = JSONObject.toJSONString(params);
                StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8");
                httpPut.setEntity(stringEntity);
            }
            response = client.execute(httpPut);
            HttpEntity entity = response.getEntity();
            String jsons = EntityUtils.toString(entity);
            return new String(jsons.getBytes(decode), encode);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("关闭put-response请求出错：" + e.toString());
            }
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                log.error("关闭put-client请求出错：" + e.toString());
            }
        }
    }

    /**
     * delete请求
     *
     * @param url
     * @param headers
     * @param encode
     * @return
     */
    public static String doDelete(String url, Map<String, Object> headers, String encode, String decode) throws Exception {
        if (encode == null) {
            encode = "utf-8";
        }
        if (decode == null) {
            decode = "utf-8";
        }
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClientBuilder.create().build();
            HttpDelete httpDelete = new HttpDelete(url);
            //设置header
            if (headers != null && !headers.isEmpty()) {
                for (String s : headers.keySet()) {
                    httpDelete.setHeader(s, headers.get(s).toString());
                }
            }

            response = client.execute(httpDelete);
            HttpEntity entity = response.getEntity();
            String jsons = EntityUtils.toString(entity);
            return new String(jsons.getBytes(decode), encode);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("关闭delete-response同步请求出错：" + e.toString());
            }
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                log.error("关闭delete-client同步请求出错：" + e.toString());
            }
        }
    }

}
